package com.cby.android.base.handler

import android.os.*
import android.util.Log

/**
 * @author ChenBaoyang
 * @description: ThreadHelper
 * @date 2021/10/18 14:33
 */
object ThreadHelper {

    private var thread: SingleThread? = null

    class SingleThread(private val work: WorkTask,
                       private val doMainThread:Boolean,
                       private var notifyMainThread: Boolean) : Thread() {

        companion object{
            const val ON_WORK:Int = 0x001
            const val ON_FINISH:Int = 0x002
        }


        private var looper: Looper? = null
        private var handler: Handler? = null

        override fun run() {
            Looper.prepare() //创建与当前线程相关的Looper

            looper = if (doMainThread) {
                Looper.getMainLooper()
            }else{
                Looper.myLooper()
            } //获取当前线程的Looper对象
            Log.d("HandlerThreadActivity", "Thread3------" + currentThread())
            handler = InternalHandler(looper!!)
            //执行work接口的操作
            sendMessage(work)
            Looper.loop() //调用此方法，消息才会循环处理
        }

        fun quit() {
            looper?.quit()
        }

        private fun sendMessage(work: WorkTask) {
            val message: Message? = handler?.obtainMessage(ON_WORK, work)
            message?.sendToTarget()
        }

        inner class InternalHandler(looper: Looper?) : Handler(looper!!) {
            override fun handleMessage(msg: Message) {
                val work: WorkTask = msg.obj as WorkTask
                when (msg.what) {
                    ON_WORK -> onWork()
                    ON_FINISH -> work.onFinish()
                }
            }
        }

        private fun onWork() {
            work.doWork()
            val isOnMain = handler?.looper == Looper.getMainLooper()
            if(notifyMainThread) {
                if(!isOnMain) {
                    handler = InternalHandler(Looper.getMainLooper())
                }
                val message: Message? = handler?.obtainMessage(ON_FINISH, work)
                message?.sendToTarget()
            }else{
                work.onFinish()
            }

        }
    }

    interface WorkTask{
        fun doWork()
        fun onFinish()
    }




    fun handWork(workTask: WorkTask, isMainThread: Boolean, endMainThread: Boolean = false) {
        thread = SingleThread(workTask, isMainThread, endMainThread)
        thread?.start()
    }

    fun quitWork() {
        thread?.quit()
    }

}